Rの並列化(doMC)

doMCパッケージを用いて指定したCPUコア数にタスクを分割
foreachパッケージを用いて処理を並列化

library(doMC)
## Loading required package: foreach
## Loading required package: iterators
## Loading required package: codetools
## Loading required package: multicore
N <- 10^4
cores <- 1:8
r <- rep(NA, length(cores))
for (i in cores) {
    registerDoMC(i)
    r[i] <- system.time(foreach(i = 1:N, .combine = "c") %dopar% mean(rnorm(N)))[3]
}

plot(cores, r/r[1], type = "b", xlab = "number of cores", ylab = "relative time compared with single core")
abline(v = 4, lty = 4, col = "red")
title(main = "Parallel computing by doMC + foreach")

plot of chunk unnamed-chunk-1

print(data.frame(cores, time = r, relative = r/r[1]))
##   cores  time relative
## 1     1 24.12   1.0000
## 2     2 15.26   0.6325
## 3     3 12.52   0.5192
## 4     4 11.18   0.4637
## 5     5 11.27   0.4673
## 6     6 11.25   0.4663
## 7     7 11.08   0.4596
## 8     8 11.37   0.4712